//
//  SettingView.swift
//  jiweiapp
//
//  Created by Kin Wong on 15/8/14.
//  Copyright (c) 2015年 Kin Wong. All rights reserved.
//

import UIKit

class SettingView: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var settingView: UITableView?
    var settingItems: [String]?
    let notification = "Nofi"
    var notificationSwitch: Bool?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        self.settingItems = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")!) as? Array
        
        self.settingView = UITableView(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-60), style: UITableViewStyle.Plain) //实例化列表
        self.settingView!.delegate = self
        self.settingView!.dataSource = self //设置数据来源
        self.settingView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SettingCell") //创建列表单元
        self.settingView!.tableFooterView = UIView(frame: CGRectZero) //隐藏多余的分割线
        self.view.addSubview(self.settingView!) //显示部件
        // Do any additional setup after loading the view.
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.settingItems!.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let id: String = "SettingCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(id, forIndexPath: indexPath) as! UITableViewCell
        let messageswitch = UISwitch()
        
        messageswitch.addTarget(self, action: Selector("changeSwitchBool:"), forControlEvents: UIControlEvents.ValueChanged)
        readDefaultSettings()
        messageswitch.on = self.notificationSwitch!
        
        cell.accessoryType = UITableViewCellAccessoryType.None
        cell.textLabel?.text = self.settingItems![indexPath.row]
        
        if indexPath.row == 0 {
            cell.accessoryView = messageswitch
        }
        
        return cell
    }
    
    func changeSwitchBool(switchState: UISwitch) {
        NSUserDefaults.standardUserDefaults().setBool(switchState.on, forKey: "Nofi")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
    
    func readDefaultSettings() {
        self.notificationSwitch = NSUserDefaults.standardUserDefaults().boolForKey("Nofi") as Bool!
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
